﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BLL;
using SMSModels;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SMSUI.GoodsManager
{
    public partial class FrmReturnGoods : Form
    {
        private BLL.GoodsManager.ReturnGoodsManager returnGoodsManager = new BLL.GoodsManager.ReturnGoodsManager();
        private BLL.QueryStatistics.BorrowGoodsQueryManager borrowGoodsManager = new BLL.QueryStatistics.BorrowGoodsQueryManager();

        List<BorrowGoods> bgls;
        List<string> printList = new List<string>();
        public FrmReturnGoods()
        {
            InitializeComponent();
            bgls = borrowGoodsManager.GetBorrowGoodsInfoList();
        }
        //窗体加载
        private void FrmReturnGoods_Load(object sender, EventArgs e)
        {
            //绑定数据到dgv
            DataSet ds = returnGoodsManager.GetDataSetFromReturnGoodsTable();
            dgvReturnGoodsInfo.DataSource = ds.Tables[0];
            //绑定数据到还货单位
            cmbReturnGoodsUnit.DataSource = bgls;
            cmbReturnGoodsUnit.DisplayMember = "BorrowGoodsUnits";
            cmbReturnGoodsUnit.SelectedIndex = -1;
            //绑定数据到货物编号
            cmbGoodsID.DataSource = bgls;
            cmbGoodsID.DisplayMember = "GoodsID";
            cmbGoodsID.SelectedIndex = -1;
            //绑定数据到货物名称
            cmbGoodsName.DataSource = bgls;
            cmbGoodsName.DisplayMember = "GoodsName";
            cmbGoodsName.SelectedIndex = -1;
            //绑定数据到规格
            cmbGoodsSpec.DataSource = bgls;
            cmbGoodsSpec.DisplayMember = "Spec";
            cmbGoodsSpec.SelectedIndex = -1;
            //绑定数据到计量单位
            cmbGoodsUnits.DataSource = bgls;
            cmbGoodsUnits.DisplayMember = "Units";
            cmbGoodsUnits.SelectedIndex = -1;
            //绑定数据到仓库名称
            cmbStoreName.DataSource = bgls;
            cmbStoreName.DisplayMember = "StoreName";
            cmbStoreName.ValueMember = "StoreID";
            cmbStoreName.SelectedIndex = -1;

            DeleDOC();
        }
        //退出
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //列表单击
        private void dgvReturnGoodsInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            cmbReturnGoodsUnit.Text = dgvReturnGoodsInfo[1,dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            txtReturnGoodsMan.Text = dgvReturnGoodsInfo[2,dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            txtPhone.Text = dgvReturnGoodsInfo[3, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            cmbGoodsID.Text = dgvReturnGoodsInfo[4, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            cmbGoodsName.Text = dgvReturnGoodsInfo[5, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            cmbGoodsSpec.Text = dgvReturnGoodsInfo[6, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            cmbGoodsUnits.Text = dgvReturnGoodsInfo[7, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            cmbStoreName.Text = dgvReturnGoodsInfo[9, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            txtReturnGoodsQuanty.Text = dgvReturnGoodsInfo[10, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            txtReturnGoodsTime.Text = dgvReturnGoodsInfo[11, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            txtHander.Text = dgvReturnGoodsInfo[12, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();
            txtRemarks.Text = dgvReturnGoodsInfo[13, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString();

        }

        //还货
        private void btnReturnGoods_Click(object sender, EventArgs e)
        {
            if (cmbReturnGoodsUnit.SelectedIndex==-1 || txtReturnGoodsMan.Text.Length == 0 || txtPhone.Text.Length == 0 || cmbGoodsID.SelectedIndex==-1 || cmbGoodsName.SelectedIndex == -1 || cmbGoodsUnits.SelectedIndex == -1 || cmbGoodsSpec.SelectedIndex == -1 || cmbStoreName.SelectedIndex == -1 || txtReturnGoodsQuanty.Text.Trim().Length == 0 || txtHander.Text.Trim().Length == 0)
            {
                MessageBox.Show("请填写完整！");
            }
            else
            {
                ReturnGoods returnGoods = new ReturnGoods
                {
                    ReturnGoodsID = "hh" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                    ReturnGoodsUnits = cmbReturnGoodsUnit.Text,
                    Returner=txtReturnGoodsMan.Text.Trim(),
                    ReturnerPhone =txtPhone.Text.Trim(),
                    GoodsID=cmbGoodsID.Text,
                    GoodsName=cmbGoodsName.Text,
                    GoodsSpec=cmbGoodsSpec.Text,
                    Units=cmbGoodsUnits.Text,
                    StoreID=Convert.ToInt32(cmbStoreName.SelectedValue),
                    StoreName=cmbStoreName.Text,
                    ReturnGoodsQuantity=Convert.ToInt32(txtReturnGoodsQuanty.Text.Trim()),
                    ReturnGoodsTime= DateTime.Now.ToString("yyyy年MM月dd日HH时mm分"),
                    Handler=txtHander.Text.Trim(),
                    Remarks=txtRemarks.Text.Trim()
                };
                if (returnGoodsManager.ReturnGoods(returnGoods)>0 && returnGoodsManager.UpdateStorageOnReturnGoods(returnGoods)>0)
                {
                    MessageBox.Show("还货成功！");
                    FrmReturnGoods_Load(sender, e);
                }
                else
                {
                    MessageBox.Show("还货失败！请检查！");
                }
            }
        }
        //修改
        private void btnRevise_Click(object sender, EventArgs e)
        {
            string oldTime = txtReturnGoodsTime.Text;
            if (cmbReturnGoodsUnit.SelectedIndex == -1 || txtReturnGoodsMan.Text.Length == 0 || txtPhone.Text.Length == 0 || cmbGoodsID.SelectedIndex == -1 || cmbGoodsName.SelectedIndex == -1 || cmbGoodsUnits.SelectedIndex == -1 || cmbGoodsSpec.SelectedIndex == -1 || cmbStoreName.SelectedIndex == -1 || txtReturnGoodsQuanty.Text.Trim().Length == 0 || txtHander.Text.Trim().Length == 0)
            {
                MessageBox.Show("请填写完整！");
            }
            else
            {
                ReturnGoods returnGoods = new ReturnGoods
                {
                    ReturnGoodsID = dgvReturnGoodsInfo[0, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(),
                    ReturnGoodsUnits = cmbReturnGoodsUnit.Text,
                    Returner = txtReturnGoodsMan.Text.Trim(),
                    ReturnerPhone = txtPhone.Text.Trim(),
                    GoodsID = cmbGoodsID.Text,
                    GoodsName = cmbGoodsName.Text,
                    GoodsSpec = cmbGoodsSpec.Text,
                    Units = cmbGoodsUnits.Text,
                    StoreID = Convert.ToInt32(cmbStoreName.SelectedValue),
                    StoreName = cmbStoreName.Text,
                    ReturnGoodsQuantity = Convert.ToInt32(txtReturnGoodsQuanty.Text.Trim()),
                    //ReturnGoodsTime = DateTime.Now.ToString("yyyy年MM月dd日HH时mm分"),
                    ReturnGoodsTime = oldTime,
                    Handler = txtHander.Text.Trim(),
                    Remarks = txtRemarks.Text.Trim()
                };
                if (returnGoodsManager.ReviseReturnGoodsInfo(returnGoods) > 0)
                {
                    MessageBox.Show("修改成功！");
                    FrmReturnGoods_Load(sender, e);
                }
                else
                {
                    MessageBox.Show("修改失败！请检查！");
                }
            }
        }
        //删除
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvReturnGoodsInfo.CurrentCell != null && dgvReturnGoodsInfo.CurrentCell.RowIndex != -1)
            {
                ReturnGoods returnGoods = new ReturnGoods
                {
                    ReturnGoodsID = dgvReturnGoodsInfo[0, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString()

                };

                if (returnGoodsManager.DeleteReturnGoodsInfo(returnGoods) > 0)
                {
                    MessageBox.Show("删除成功！");
                    FrmReturnGoods_Load(sender, e);
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
            else
            {
                MessageBox.Show("请在列表中选择要删除的记录！", "提示");
            }
        }
        //弹出添加打印菜单
        private void dgvReturnGoodsInfo_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button==MouseButtons.Right)
            {
                cmsAddPrint.Show(MousePosition.X,MousePosition.Y);
            }
        }
        //添加到待打印
        private void 添加到待打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string printNote = string.Format("{0}#{1}#{2}#{3}#{4}#{5}#{6}#{7}#{8}#{9}#{10}#{11}", dgvReturnGoodsInfo[0, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[1, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[2, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[3, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[4, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[5, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[6, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[7, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[9, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[10, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[11, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString(), dgvReturnGoodsInfo[12, dgvReturnGoodsInfo.CurrentCell.RowIndex].Value.ToString());
            if (printList.Contains(printNote))  //待打印记录已存在
            {
                return;
            }
            else
            {
                if (printList.Count >= 10)
                {
                    MessageBox.Show("一次只能添加打印10条记录！默认A4纸，太多放不下！");
                    return;
                }
                printList.Add(printNote);
                btnPrint.Text = "打印 " + printList.Count + "条";

            }
        }
        //打印按钮单击
        private void btnPrint_Click(object sender, EventArgs e)
        {
            //删除存在的入库单
            DeleDOC();
            //写入表格数据
            if (printList.Count == 0)
            {
                MessageBox.Show("请在列表中右键添加待打印的还货记录！");
            }
            else
            {
                #region 创建待打印word
                //创建一个文档对象
                Document doc = new Document();
                //添加一个section
                Section section = doc.AddSection();

                //纸张横向
                Section sec = doc.Sections[0];
                sec.PageSetup.Orientation = PageOrientation.Landscape;

                //添加标题
                Paragraph inStoreTitle = section.AddParagraph();
                inStoreTitle.AppendText("还货单");
                //设置标题格式
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Black;
                style1.CharacterFormat.FontName = "方正小标宋简体";
                style1.CharacterFormat.FontSize = 24f;
                doc.Styles.Add(style1);
                inStoreTitle.ApplyStyle("titleStyle");
                //标题居中
                inStoreTitle.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                //添加单号
                Paragraph pStrat = section.AddParagraph();
                pStrat.AppendText("单号：hhd" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                //设置单号格式
                ParagraphStyle style12 = new ParagraphStyle(doc);
                style12.Name = "oddNumStyle";
                style12.CharacterFormat.Bold = false;
                style12.CharacterFormat.TextColor = Color.Black;
                style12.CharacterFormat.FontName = "宋体";
                style12.CharacterFormat.FontSize = 12f;
                doc.Styles.Add(style12);
                pStrat.ApplyStyle("oddNumStyle");

                //添加表格
                //Section section = doc.AddSection(); //添加section
                Table table = section.AddTable(true);
                //指定表格的行数和列数（11行，11列）
                table.ResetCells(11, 12);

                //标题行数组
                string[] tabTitle = { "还货编号", "还货单位", "还货人", "联系电话", "货物编号", "货物名称", "规格", "计量单位", "仓库名称", "还货数量", "还货时间", "经手人" };
                //添加表格标题行
                for (int i = 0; i < 1; i++)
                {
                    for (int j = 0; j < 12; j++)
                    {
                        TextRange range = table[i, j].AddParagraph().AppendText(tabTitle[j]);
                        range.CharacterFormat.FontName = "黑体";
                        range.CharacterFormat.FontSize = 12;
                        range.CharacterFormat.TextColor = Color.Black;
                        range.CharacterFormat.Bold = false;
                        table[i, j].Paragraphs[0].Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;  //水平居中
                        table[i, j].CellFormat.VerticalAlignment = VerticalAlignment.Middle;    //垂直居中
                    }
                }

                //遍历打印列表并插入表格数据
                for (int i = 0; i < printList.Count; i++)
                {
                    string[] arr = printList[i].Split('#');
                    for (int j = 0; j < 12; j++)
                    {
                        TextRange range = table[i + 1, j].AddParagraph().AppendText(arr[j]);
                        range.CharacterFormat.FontName = "宋体";
                        range.CharacterFormat.FontSize = 10;
                        range.CharacterFormat.TextColor = Color.Black;
                        range.CharacterFormat.Bold = false;
                        table[i + 1, j].CellFormat.VerticalAlignment = VerticalAlignment.Middle;    //垂直居中
                    }
                }
                //添加签字栏
                Paragraph pEnd = section.AddParagraph();
                pEnd.AppendText("制单人：              审核人：              日期：    年  月  日");
                //设置签字栏格式
                ParagraphStyle style13 = new ParagraphStyle(doc);
                style13.Name = "endLineStyle";
                style13.CharacterFormat.Bold = false;
                style13.CharacterFormat.TextColor = Color.Black;
                style13.CharacterFormat.FontName = "宋体";
                style13.CharacterFormat.FontSize = 12f;
                doc.Styles.Add(style13);
                pEnd.ApplyStyle("endLineStyle");

                //保存文档
                doc.SaveToFile("./returnGoodsDoc.docx", FileFormat.Docx2013);
                #endregion

                System.Threading.Thread.Sleep(1000);

                #region 开始打印
                //初始化PrintDialog实例
                PrintDialog dialog = new PrintDialog();

                //设置打印对话框属性
                dialog.AllowPrintToFile = true;
                dialog.AllowCurrentPage = true;
                dialog.AllowSomePages = true;

                //设置文档打印对话框
                doc.PrintDialog = dialog;

                //显示打印对话框并点击确定执行打印
                System.Drawing.Printing.PrintDocument printDoc = doc.PrintDocument;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    printDoc.Print();
                }
                DeleDOC();
                #endregion
            }
        }
        //弹出清空待打印菜单
        private void btnPrint_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                cmsClearPrintList.Show(MousePosition.X, MousePosition.Y);
            }
        }
        //清空待打印
        private void 清空待打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            printList.Clear();
            btnPrint.Text = "打印";
        }

        /// <summary>
        /// 删除returnGoodsDoc.docx文件
        /// </summary>
        public void DeleDOC()
        {
            if (System.IO.File.Exists("./returnGoodsDoc.docx"))
            {
                System.IO.File.Delete("./returnGoodsDoc.docx");
            }
        }
    }
}
